//
//  WWebViewController.m
//  wzqproject
//
//  Created by 吴志强 on 2017/12/13.
//  Copyright © 2017年 吴志强. All rights reserved.
//

#import "WWebViewController.h"
#import "UIScrollView+MJRefresh.h"
#import "UIScrollView+MJExtension.h"
#import "MJRefreshNormalHeader.h"
#import "MJRefreshAutoNormalFooter.h"

#define UI_IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)

    //判断iPHoneXr
#define SCREENSIZE_IS_XR ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(828, 1792), [[UIScreen mainScreen] currentMode].size) && !UI_IS_IPAD : NO)

    //判断iPHoneX、iPHoneXs
#define SCREENSIZE_IS_X ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) && !UI_IS_IPAD : NO)
#define SCREENSIZE_IS_XS ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) && !UI_IS_IPAD : NO)


@interface WWebViewController ()<UINavigationControllerDelegate>

@property (nonatomic,strong) UIView *indacator;

@end

@implementation WWebViewController

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];

//    [self.navigationController setNavigationBarHidden:YES animated:YES];

    __weak typeof(UIView *)weakSelf = _indacator;
    [UIView animateWithDuration:0.3 animations:^{

        weakSelf.alpha = 0;
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(10, 20, 55, 30);
    [btn setImage:[UIImage imageNamed:@"back_black"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:btn];

    UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem = back;

    [self initWebView];
}

- (void) setShowLeftBtn:(BOOL)showLeftBtn
{
    _showLeftBtn = showLeftBtn;
    if (_showLeftBtn) {

        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(10, 20, 55, 30);
        btn.layer.cornerRadius = 15;
        btn.backgroundColor = [UIColor grayColor];
        [btn setTitle:@"返回" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        btn.titleLabel.font = [UIFont systemFontOfSize:16];
        [self.view addSubview:btn];

    }else{

        self.navigationItem.leftBarButtonItem = nil;
    }
}

/**
 显示返回取消的按钮(present出来的页面使用)
 */
- (void) showDismissBtns;
{
    self.showLeftBtn = YES;
}

-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 设置webview视图
+ (WKProcessPool *)singleWkProcessPool
{
    static dispatch_once_t onceToken;
    static WKProcessPool *sharedPool;
    dispatch_once(&onceToken, ^{
        sharedPool = [[WKProcessPool alloc] init];
    });
    return sharedPool;
}

/**
 初始化webview
 */
-(void)initWebView
{
    WKWebViewConfiguration *wkConfig = [[WKWebViewConfiguration alloc] init];
    
    //使用单例 解决locastorge 储存问题
    wkConfig.processPool = [WWebViewController singleWkProcessPool];
    //取消播放控制器
    if (@available(iOS 10.0, *)) {
        wkConfig.mediaTypesRequiringUserActionForPlayback = YES;
    } else {
            // Fallback on earlier versions
    }
    wkConfig.allowsInlineMediaPlayback = YES;

    float hegiht = 64;
    if (SCREENSIZE_IS_XR || SCREENSIZE_IS_X || SCREENSIZE_IS_XS) {
        hegiht = 88;
    }

    //初始化并指定代理
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - hegiht) configuration:wkConfig];

    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    self.webView.scrollView.showsVerticalScrollIndicator = NO;
    self.webView.scrollView.showsHorizontalScrollIndicator = NO;
    self.webView.backgroundColor = [UIColor whiteColor];
    self.webView.scrollView.backgroundColor = [UIColor whiteColor];

    //适配机型
    if (@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }

    //添加到控制器上
    [self.view addSubview:self.webView];
}

#pragma mark - 设置方法
/**
 设置进度

 @param process 进度
 */
-(void)setProcess:(float)process
{
    if (!_disableIndicator) {

        if (!_indacator) {

            _indacator = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 2)];
            _indacator.backgroundColor = [UIColor blackColor];
            [[UIApplication sharedApplication].keyWindow addSubview:_indacator];
        }
    }
    __weak typeof(UIView *)weakSelf = _indacator;
    [UIView animateWithDuration:0.5 animations:^{

        self.indacator.width = process*[[UIScreen mainScreen] bounds].size.width;
    } completion:^(BOOL finished) {

        if (process == 1.0) {

            [UIView animateWithDuration:0.3 animations:^{

                weakSelf.alpha = 0;
            }];
        }
    }];
}

/**
 清除缓存

 @param clearCache 默认不清除
 */
-(void)setClearCache:(BOOL)clearCache
{
    _clearCache = clearCache;

    if (_clearCache) {

        if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
            NSSet *websiteDataTypes= [NSSet setWithArray:@[
                                                           WKWebsiteDataTypeDiskCache,
                                                           WKWebsiteDataTypeMemoryCache,
                                                           WKWebsiteDataTypeCookies,
                                                           ]];

            NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
            [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{

            }];
            [[NSURLCache sharedURLCache] removeAllCachedResponses];
        }
        else {
                //先删除cookie
            NSHTTPCookie *cookie;
            NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
            for (cookie in [storage cookies])
                {
                [storage deleteCookie:cookie];
                }

            NSString *libraryDir = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString *bundleId  =  [[[NSBundle mainBundle] infoDictionary]
                                    objectForKey:@"CFBundleIdentifier"];
            NSString *webkitFolderInLib = [NSString stringWithFormat:@"%@/WebKit",libraryDir];
            NSString *webKitFolderInCaches = [NSString
                                              stringWithFormat:@"%@/Caches/%@/WebKit",libraryDir,bundleId];
            NSString *webKitFolderInCachesfs = [NSString
                                                stringWithFormat:@"%@/Caches/%@/fsCachedData",libraryDir,bundleId];
            NSError *error;
            /* iOS8.0 WebView Cache的存放路径 */
            [[NSFileManager defaultManager] removeItemAtPath:webKitFolderInCaches error:&error];
            [[NSFileManager defaultManager] removeItemAtPath:webkitFolderInLib error:nil];
            /* iOS7.0 WebView Cache的存放路径 */
            [[NSFileManager defaultManager] removeItemAtPath:webKitFolderInCachesfs error:&error];
            NSString *cookiesFolderPath = [libraryDir stringByAppendingString:@"/Cookies"];
            [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&error];
            [[NSURLCache sharedURLCache] removeAllCachedResponses];
        }
    }
}

/**
 设置取消页面加载进度条

 @param disableIndicator 是否取消，默认是有的
 */
-(void)setDisableIndicator:(BOOL)disableIndicator
{
    _disableIndicator = disableIndicator;

    if (!_disableIndicator) {

        _indacator = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 2)];
        _indacator.backgroundColor = [UIColor blackColor];
        [[UIApplication sharedApplication].keyWindow addSubview:_indacator];
    }else{

        [_indacator removeFromSuperview];
        _indacator = nil;
    }
}

-(void)close
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 刷新webview
/**
 请求网络

 @param url 要加载的url字符串
 */
-(void)loadRequestURLString:(NSString *)url;
{
    //1.是否清除缓存
    if (self.clearCache) {
        self.clearCache = YES;
    }

    NSURL *urls = [NSURL URLWithString:url];

    NSURLRequest *request = [NSURLRequest requestWithURL:urls];

    //4.请求页面
    [self.webView loadRequest:request];
}

#pragma mark - 监听脚本事件

#pragma mark - WKNavigationDelegate来追踪加载过程
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation;
{
    [self setProcess:0.3];

    webView.scrollView.scrollEnabled = NO;
}

// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation;
{
    [self.webView.scrollView.mj_header endRefreshing];

    [self setProcess:0.6];
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation;
{
    [self.webView.scrollView.mj_header endRefreshing];

    [self setProcess:1.0];

    //添加标题
    if (self.title.length == 0) {
        self.title = self.webView.title;
    }

    webView.scrollView.scrollEnabled = YES;
}

#pragma mark - WKNavigtionDelegate来进行页面跳转
// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler;
{
    decisionHandler(WKNavigationResponsePolicyAllow);//崩在这里
}

// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;
{
    decisionHandler(WKNavigationActionPolicyAllow);
}

@end
